#include "menu.h"

/******************************************************
					menu_item
******************************************************/

menu::menu_item::menu_item(label *a, label *b, short n, void (*act)(short)){
	set(a, b, n, act);
}

void menu::menu_item::set(label *a, label *b, short n, void (*act)(short)){
	active = 0;
	action = act;

	active_l = a;
	nactive_l = b;
	current_l = nactive_l;

	id = n;
	x = 0;
	y = 0;
}

void menu::menu_item::set_activity(bool act){
	active = act;

	//set appropriate look
	if(act){
		current_l = active_l;
	}
	else{
		current_l = nactive_l;
	}
}

void menu::menu_item::do_action(){
	action(id);
}

short menu::menu_item::get_height(){
	return current_l->get_height();
}

short menu::menu_item::get_width(){
	return current_l->get_width();
}

void menu::menu_item::set_xy(short nx, short ny){
	x = nx;
	y = ny;
}

void menu::menu_item::draw(SDL_Surface *target){
	//draw label
	current_l->draw(target,x,y);
}

/******************************************************
					menu_world
******************************************************/

void menu::menu_world::add_item(menu_item& new_item){
	items.push_back(new_item);
}

void menu::menu_world::draw(SDL_Surface* target, SDL_Rect* dest){
	
	printf("w %d h %d x %d y %d\n", dest->w, dest->h, dest->x, dest->y);
	//calculate menu height
	list<menu_item>::iterator itr;
	short h = 0; //result
	for(itr = items.begin() ; itr != items.end() ; itr++){
		h += itr->get_height();
	}	

	//draw background
	SDL_Rect back_dest = *dest;
	SDL_BlitSurface(background, NULL, target, &back_dest);

	//calculate menu item coordinates and draw
	short y = dest->y + (dest->h - h)/2;
	short x;
	for(itr = items.begin() ; itr != items.end() ; itr++){
		x = dest->w;//(dest.w - itr->get_width())/2;
		itr->set_xy(x,y);
		itr->draw(target);
		y += itr->get_height();
	}
}

void menu::menu_world::refresh(int tics){

}

void menu::menu_world::select_first(){
	current = items.begin();
	current->set_activity(1);
}


void menu::menu_world::react(SDL_Event& ev){
	if(ev.type == SDL_KEYDOWN){
		//we deal only with keyboard
		if(ev.key.keysym.sym == SDLK_UP){
			//unactivate current item
			current->set_activity(0);
			//find previous item
			if(current == items.begin()){
				current = --items.end();
			}
			else{
				current--;
			}
			//activate it
			current->set_activity(1);
		}
		else if(ev.key.keysym.sym == SDLK_DOWN){
			//unactivate current item
			current->set_activity(0);
			//find next item
			current++;
			if(current == items.end()){
				current = items.begin();
			}
			//activate it
			current->set_activity(1);
		}
		else if(ev.key.keysym.sym == SDLK_RETURN){
			//call action of selected element
			exit(0);
			//current->do_action();
		}
		else if(ev.key.keysym.sym == SDLK_ESCAPE){
			//restore previous menuworld
		}
	}
}

void menu::menu_world::set_background(SDL_Surface* img){
	background = img;
}

